<template>
  <div class="service-dashboard-page">
    <div class="container">
      <!-- 头部 -->
      <div class="header">
        <h1 class="title">👨‍💼 客服工作台</h1>
        <div class="status-info">
          <span class="status-label">连接状态：</span>
          <span class="status-badge" :class="{ connected: isConnected }">
            {{ isConnected ? '🟢 已连接' : '🔴 未连接' }}
          </span>
        </div>
      </div>

      <!-- 连接提示（未连接时显示，自动连接） -->
      <div v-if="!isConnected" class="login-section">
        <div class="login-card">
          <h3>准备连接</h3>
          <div class="info-text">
            <p>将使用您的账号ID作为客服ID：<strong>{{ serviceId }}</strong></p>
            <p class="hint">正在建立连接...</p>
          </div>
        </div>
      </div>

      <!-- 工作台（连接后显示） -->
      <div v-else class="dashboard-container">
        <div class="dashboard-layout">
          <!-- 左侧：在线用户列表 -->
          <div class="users-sidebar">
            <div class="sidebar-header">
              <h3>在线用户</h3>
              <span class="user-count">{{ onlineUsers.length }}</span>
            </div>
            <div v-if="onlineUsers.length === 0" class="no-users">
              <p>暂无在线用户</p>
            </div>
            <div v-else class="users-list">
              <div
                v-for="user in onlineUsers"
                :key="user.user_id"
                class="user-item"
                :class="{ active: currentUserId === user.user_id }"
                @click="selectUser(user)"
              >
                <span class="user-icon">👤</span>
                <div class="user-info">
                  <span class="user-name">{{ user.user_name || `用户${user.user_id}` }}</span>
                  <span class="user-id">ID: {{ user.user_id }}</span>
                </div>
                <span v-if="getUnreadCount(user.user_id) > 0" class="unread-badge">
                  {{ getUnreadCount(user.user_id) }}
                </span>
              </div>
            </div>
          </div>

          <!-- 右侧：聊天区域 -->
          <div class="chat-area">
            <div v-if="!currentUserId" class="no-selection">
              <div class="no-selection-content">
                <span class="icon">💬</span>
                <p>请选择一个用户开始聊天</p>
              </div>
            </div>

            <div v-else class="chat-container">
              <!-- 聊天头部 -->
              <div class="chat-header">
                <div class="user-info">
                  <span class="user-icon">👤</span>
                  <div>
                    <span class="user-name">{{ currentUserName || `用户${currentUserId}` }}</span>
                    <span class="user-id">ID: {{ currentUserId }}</span>
                  </div>
                </div>
                <button class="disconnect-btn" @click="disconnectFromUser">
                  结束对话
                </button>
              </div>

              <!-- 消息列表 -->
              <div class="messages-container" ref="messagesContainer">
                <div
                  v-for="(msg, index) in currentMessages"
                  :key="index"
                  class="message-item"
                  :class="msg.type"
                >
                  <div v-if="msg.type === 'system'" class="system-message">
                    <span class="system-icon">ℹ️</span>
                    <span>{{ msg.content }}</span>
                  </div>
                  <div v-else-if="msg.type === 'chat'" class="chat-message" :class="msg.from === 'service' ? 'mine' : 'other'">
                    <div class="message-header">
                      <span class="sender-name">{{ msg.from === 'service' ? '我' : '用户' }}</span>
                      <span class="message-time">{{ msg.time }}</span>
                    </div>
                    <div class="message-content">{{ msg.content }}</div>
                  </div>
                  <div v-else-if="msg.type === 'error'" class="error-message">
                    <span class="error-icon">⚠️</span>
                    <span>{{ msg.content }}</span>
                  </div>
                </div>
              </div>

              <!-- 输入区域 -->
              <div class="input-area">
                <input
                  v-model="messageInput"
                  type="text"
                  placeholder="输入消息..."
                  class="message-input"
                  @keyup.enter="sendMessage"
                  :disabled="!currentUserId"
                />
                <button
                  class="send-btn"
                  @click="sendMessage"
                  :disabled="!currentUserId || !messageInput.trim()"
                >
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作栏 -->
        <div class="footer-actions">
          <button class="logout-btn" @click="disconnect">退出登录</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { customerServiceWS } from '@/utils/customerServiceWebSocket'

const userStore = useUserStore()
const router = useRouter()

// 状态
const isConnected = ref(false)
const currentUserId = ref('') // 当前选中的用户ID（用于聊天）
const currentUserName = ref('') // 当前选中的用户名称
const onlineUsers = ref([])
const messages = ref({}) // { [userId]: Message[] }
const messageInput = ref('')
const messagesContainer = ref(null)

let messageHandler = null

// 获取当前登录用户的ID和名称（作为客服ID）
const serviceId = computed(() => {
  return userStore.userInfo?.id ? String(userStore.userInfo.id) : ''
})

const serviceName = computed(() => {
  return userStore.userInfo?.nickname || userStore.userInfo?.name || userStore.userInfo?.username || '客服'
})

// 获取当前用户的消息列表
const currentMessages = computed(() => {
  return messages.value[currentUserId.value] || []
})

// 获取未读消息数
const getUnreadCount = (userId) => {
  const userMessages = messages.value[userId] || []
  return userMessages.filter(msg => msg.type === 'chat' && msg.from === 'user' && !msg.read).length
}

// 客服端连接
const connectAsService = () => {
  if (!serviceId.value) {
    alert('请先登录')
    return
  }

  const success = customerServiceWS.connectAsService(
    serviceId.value,
    serviceName.value
  )

  if (success) {
    // 监听消息
    messageHandler = customerServiceWS.onMessage((message) => {
      handleMessage(message)
    })

    // 监听连接状态
    checkConnectionStatus()
  } else {
    alert('连接失败，请重试')
  }
}

// 检查连接状态
const checkConnectionStatus = () => {
  const interval = setInterval(() => {
    isConnected.value = customerServiceWS.isConnected
    if (!isConnected.value) {
      clearInterval(interval)
    }
  }, 500)
}

// 自动连接（进入页面后若未连接则自动连接）
onMounted(() => {
  if (!isConnected.value && serviceId.value) {
    connectAsService()
  }
})

// 处理收到的消息
const handleMessage = (message) => {
  if (message.type === 'system') {
    const systemMsg = {
      type: 'system',
      content: message.message || '系统消息',
      time: new Date().toLocaleTimeString()
    }

    // 如果是新用户加入的消息
    if (message.user_id && message.user_name) {
      // 检查用户是否已在列表中
      const existingUser = onlineUsers.value.find(u => u.user_id === message.user_id)
      if (!existingUser) {
        onlineUsers.value.push({
          user_id: message.user_id,
          user_name: message.user_name
        })
      }
    }

    // 如果是用户离开的消息
    if (message.message && message.message.includes('已离开')) {
      const userId = message.user_id
      if (userId) {
        onlineUsers.value = onlineUsers.value.filter(u => u.user_id !== userId)
        if (currentUserId.value === userId) {
          currentUserId.value = ''
          currentUserName.value = ''
        }
      }
    }

    // 添加到系统消息
    if (!messages.value['system']) {
      messages.value['system'] = []
    }
    messages.value['system'].push(systemMsg)
    isConnected.value = true
  } else if (message.type === 'chat') {
    const fromUserId = message.from_id
    if (!fromUserId) return

    // 确保用户已在列表中
    const existingUser = onlineUsers.value.find(u => u.user_id === fromUserId)
    if (!existingUser) {
      onlineUsers.value.push({
        user_id: fromUserId,
        user_name: message.from_name || `用户${fromUserId}`
      })
    }

    // 添加到消息列表
    if (!messages.value[fromUserId]) {
      messages.value[fromUserId] = []
    }
    messages.value[fromUserId].push({
      type: 'chat',
      from: message.from === 'user' ? 'user' : 'service',
      content: message.content,
      time: message.time || new Date().toLocaleTimeString(),
      read: currentUserId.value === fromUserId
    })

    // 如果当前正在查看该用户的聊天，滚动到底部
    if (currentUserId.value === fromUserId) {
      scrollToBottom()
    }
  } else if (message.type === 'error') {
    const errorMsg = {
      type: 'error',
      content: message.message || '发生错误',
      time: new Date().toLocaleTimeString()
    }
    if (!messages.value['system']) {
      messages.value['system'] = []
    }
    messages.value['system'].push(errorMsg)
  }
}

// 选择用户
const selectUser = (user) => {
  currentUserId.value = user.user_id
  currentUserName.value = user.user_name

  // 初始化消息列表
  if (!messages.value[user.user_id]) {
    messages.value[user.user_id] = []
  }

  // 标记消息为已读
  if (messages.value[user.user_id]) {
    messages.value[user.user_id].forEach(msg => {
      if (msg.type === 'chat' && msg.from === 'user') {
        msg.read = true
      }
    })
  }

  scrollToBottom()
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim() || !currentUserId.value) {
    return
  }

  const content = messageInput.value.trim()

  // 客服端发送消息给指定用户
  const success = customerServiceWS.sendMessage(currentUserId.value, content)

  if (success) {
    // 添加到消息列表
    if (!messages.value[currentUserId.value]) {
      messages.value[currentUserId.value] = []
    }
    messages.value[currentUserId.value].push({
      type: 'chat',
      from: 'service',
      content: content,
      time: new Date().toLocaleTimeString()
    })
    messageInput.value = ''
    scrollToBottom()
  } else {
    if (!messages.value['system']) {
      messages.value['system'] = []
    }
    messages.value['system'].push({
      type: 'error',
      content: '发送失败，请检查连接状态',
      time: new Date().toLocaleTimeString()
    })
  }
}

// 结束与用户的对话
const disconnectFromUser = () => {
  currentUserId.value = ''
  currentUserName.value = ''
}

// 断开连接
const disconnect = () => {
  customerServiceWS.disconnect()
  isConnected.value = false
  onlineUsers.value = []
  currentUserId.value = ''
  currentUserName.value = ''
  messages.value = {}
  if (messageHandler) {
    messageHandler()
    messageHandler = null
  }
  // 退出当前页面
  setTimeout(() => {
    if (window.history.length > 1) {
      router.back()
    } else {
      router.replace('/')
    }
  }, 0)
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 清理
onUnmounted(() => {
  if (messageHandler) {
    messageHandler()
  }
  if (isConnected.value) {
    customerServiceWS.disconnect()
  }
})
</script>

<style scoped>
.service-dashboard-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-label {
  font-size: 14px;
  opacity: 0.9;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.2);
  font-size: 14px;
  font-weight: 500;
}

.status-badge.connected {
  background: rgba(34, 197, 94, 0.3);
}

.login-section {
  padding: 60px 40px;
}

.login-card {
  max-width: 400px;
  margin: 0 auto;
  padding: 32px;
  background: #f9fafb;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.login-card h3 {
  font-size: 20px;
  margin-bottom: 24px;
  text-align: center;
  color: #1f2937;
}

.info-text {
  margin-bottom: 24px;
  text-align: center;
}

.info-text p {
  margin: 8px 0;
  color: #374151;
}

.info-text strong {
  color: #667eea;
  font-size: 18px;
}

.hint {
  font-size: 14px;
  color: #9ca3af;
}

.connect-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.connect-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.dashboard-container {
  display: flex;
  flex-direction: column;
  height: 700px;
}

.dashboard-layout {
  display: grid;
  grid-template-columns: 300px 1fr;
  flex: 1;
  overflow: hidden;
}

.users-sidebar {
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  background: #f9fafb;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e5e7eb;
}

.sidebar-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #1f2937;
}

.user-count {
  padding: 4px 8px;
  background: #667eea;
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.no-users {
  padding: 40px 20px;
  text-align: center;
  color: #6b7280;
}

.users-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
}

.user-item:hover {
  background: #f3f4f6;
  border-color: #e5e7eb;
}

.user-item.active {
  background: #eef2ff;
  border-color: #667eea;
}

.user-icon {
  font-size: 24px;
}

.user-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.user-name {
  font-weight: 500;
  color: #1f2937;
  font-size: 14px;
}

.user-id {
  font-size: 12px;
  color: #6b7280;
}

.unread-badge {
  padding: 4px 8px;
  background: #ef4444;
  color: white;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  min-width: 20px;
  text-align: center;
}

.chat-area {
  display: flex;
  flex-direction: column;
  background: white;
}

.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-selection-content {
  text-align: center;
  color: #9ca3af;
}

.no-selection-content .icon {
  font-size: 64px;
  display: block;
  margin-bottom: 16px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.disconnect-btn {
  padding: 8px 16px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.disconnect-btn:hover {
  background: #dc2626;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background: #fafafa;
}

.message-item {
  margin-bottom: 16px;
}

.system-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #e0e7ff;
  border-radius: 8px;
  color: #3730a3;
  font-size: 14px;
  text-align: center;
  justify-content: center;
}

.error-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #fee2e2;
  border-radius: 8px;
  color: #991b1b;
  font-size: 14px;
  text-align: center;
  justify-content: center;
}

.chat-message {
  max-width: 70%;
}
.chat-message.other { /* 对方（用户）在左 */
  margin-right: auto;
}
.chat-message.mine { /* 我（客服）在右 */
  margin-left: auto;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.sender-name {
  font-weight: 600;
  color: #1f2937;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #6b7280;
}

.message-content {
  padding: 12px 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  color: #1f2937;
  line-height: 1.5;
  word-break: break-word;
}

.chat-message.mine .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.message-input:focus {
  border-color: #667eea;
}

.message-input:disabled {
  background: #f3f4f6;
  cursor: not-allowed;
}

.send-btn {
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.footer-actions {
  padding: 16px 24px;
  background: #f9fafb;
  border-top: 1px solid #e5e7eb;
  text-align: right;
}

.logout-btn {
  padding: 10px 20px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: background 0.2s;
}

.logout-btn:hover {
  background: #dc2626;
}

/* 滚动条样式 */
.users-list::-webkit-scrollbar,
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.users-list::-webkit-scrollbar-track,
.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.users-list::-webkit-scrollbar-thumb,
.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.users-list::-webkit-scrollbar-thumb:hover,
.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

